<?php

namespace common\rest\controllers;

use common\rest\models\c2\statics\ResponseDatum;
use Yii;
use yii\filters\ContentNegotiator;
use yii\filters\Cors;
use yii\filters\RateLimiter;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController as BaseController;
use common\rest\models\c2\statics\OperationResult;
use yii\web\Response;

/**
 * ActiveController
 */
class ActiveController extends BaseController {

    public $serializer = [
        'class' => 'common\rest\components\Serializer',
        'collectionEnvelope' => 'data',
    ];

    /**
     * @param $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        Yii::$app->response->on(\yii\web\Response::EVENT_BEFORE_SEND, function ($event) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            // $response = $event->sender;
            // if (!$response->isSuccessful) {
            //     $response->data = \common\rest\statics\ResponseDatum::getErrorDatum([
            //         'code' => !empty($response->data['code']) ? $response->data['code'] : OperationResult::ERROR_INTERNAL,
            //         'msg' => !empty($response->data['message']) ? $response->data['message'] : "",
            //     ]);
            // }
        });
        return parent::beforeAction($action);
    }

    public function behaviors()
    {
        return [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                    'application/xml' => Response::FORMAT_XML,
                ],
            ],
            [
                'class' => Cors::className(),
                'cors' => [
                    'Origin' => ['http://cxj.cross.echosite.cn', 'http://fe-yyl.lahyb.com'],
                    'Access-Control-Allow-Origin' => ['*'],
                    'Access-Control-Request-Method' => ['*'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Allow-Credentials' => true,
                    'Access-Control-Max-Age' => 3600,
                    'Access-Control-Expose-Header' => ['X-Pagination-Current-Page'],
                ],
            ],
            'verbFilter' => [
                'class' => VerbFilter::className(),
                'actions' => $this->verbs(),
            ],
            'rateLimiter' => [
                'class' => RateLimiter::className(),
            ],
        ];
    }

    public function actions() {
        $actions = parent::actions();

        // disable actions
        unset($actions['delete'], $actions['create'], $actions['update'], $actions['index']);
        // $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
       // $actions['index']['dataFilter'] = [
       //     'class' => 'yii\rest\ActiveDataFilter',
       //     'searchModel' => function () {
       //         return (new \yii\base\DynamicModel(['id' => null, 'name' => null, 'sku' => null, 'sales_price' => null]))
       //                         ->addRule('id', 'integer')
       //                         // ->addRule(['name', 'sku'], 'trim')
       //                         // ->addRule(['name', 'sku'], 'string')
       //                         ->addRule(['sku'], 'string')
       //                         ->addRule('sales_price', 'number');
       //     },
       // ];
        return $actions;
    }

    public function prepareDataProvider() {
        $requestParams = Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = Yii::$app->getRequest()->getQueryParams();
        }
        $searchModel = new $this->modelClass;

        return $searchModel->search($requestParams);
    }

    public function actionDetail($id) {
        $modelClass = $this->modelClass;
        $model = $modelClass::findOne(['id' => $id]);
        if ($model) {
            return ResponseDatum::getSuccessDatum(['message' => Yii::t('app.c2', 'Operation completed successfully!')], $model);
        } else {
            return ResponseDatum::getErrorDatum(['code' => OperationResult::ERROR_404], []);
        }
    }

}
